package com.powernode.utils;

import com.powernode.common.Constants;
import com.powernode.common.Result;
import com.powernode.controller.CustomerController;
import com.powernode.domain.Customer;
import com.powernode.domain.User;
import com.powernode.dto.CustomerDto;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class WebMvcUtils {

    /**
     * 获取request域对象
     *
     * @return
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes.getRequest();
    }

    /**
     * 获取session域对象
     *
     * @return
     */
    public static HttpSession getSession() {
        return getRequest().getSession();
    }

    /**
     * 获取ServletContext(application)域对象
     *
     * @return
     */
    public static ServletContext getApplication() {
        return ContextLoader.getCurrentWebApplicationContext().getServletContext();
    }

    /**
     * 获取response
     */
    public static HttpServletResponse getResponse() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes.getResponse();
    }

    /**
     * 获取当前用户
     */
    public static User getCurrentUser() {
        return (User) getSession().getAttribute(Constants.SESSION_USER_KEY);
    }

    /**
     * 获取当前用户名
     */
    public static String getCurrentUserName() {
        return getCurrentUser().getRealname();
    }

    /**
     * 获取当前客户
     */
    public static Customer getCurrentCustomer(){
        return (Customer) getSession().getAttribute(Constants.SESSION_CUSTOMER_KEY);
    }
}
